package com.mimo.library.common.util

import android.os.Build
import android.text.TextUtils
import java.io.*
import java.lang.Exception

/**
 * 说明：设备相关的操作类
 * @author Orange
 * @date 2021/10/5 15:20
 */
object DeviceUtil {
    /**
     * 获取CPU序列号
     *
     * @return CPU序列号(16位) 读取失败为"0000000000000000"
     */
    fun getCPUSerial(): String {
        var str = ""
        var strCPU = ""
        var cpuAddress = "0000000000000000"
        try {
            // 读取CPU信息
            val pp = Runtime.getRuntime().exec("cat /proc/cpuinfo")
            if(pp.inputStream!=null){
                val ir = InputStreamReader(pp.inputStream)
                val input = LineNumberReader(ir)
                if(input.readLine()!=null){
                    // 查找CPU序列号
                    for (i in 1..99) {
                        println("input.readLine() ：" + input.readLine())
                        if (input.readLine() != null) {
                            str = input.readLine()
                            // 查找到序列号所在行
                            if (str.indexOf("Serial") > -1) {
                                // 提取序列号
                                strCPU = str.substring(str.indexOf(":") + 1, str.length)
                                // 去空格
                                cpuAddress = strCPU.trim { it <= ' ' }
                                break
                            }
                        } else {
                            // 文件结尾
                            break
                        }
                    }
                }
            }
        } catch (ex: IOException) {
            // 赋予默认值
            ex.printStackTrace()
        }
        return cpuAddress
    }

    fun getDeviceSN(): String? {
        return Build.SERIAL
    }

    fun getCpuInfo(): String? {
        var cpuInfo = ""
        try {
            val file = File("/proc/cpuinfo")
            val reader = FileReader(file)
            val bb = CharArray(1024)
            var n: Int
            while (reader.read(bb).also { n = it } != -1) {
                println("input.readLine() ：" +String(bb, 0, n))
                cpuInfo += String(bb, 0, n)
            }
            reader.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (!TextUtils.isEmpty(cpuInfo) || cpuInfo.length > 2) {
            cpuInfo =
                cpuInfo.substring(cpuInfo.lastIndexOf(":") + 1, cpuInfo.length).trim { it <= ' ' }
        }
        return cpuInfo
    }

}